<template>
  <chart :options="options" :auto-resize="autoResize" :theme="theme" :watch-shallow="watchShallow"
         :class="className" :style="{height:height,width:width}"></chart>
</template>

<script>
  export default {
    props: {
      title: { type: String, default: '' },
      chartData: { type: Object },
      className: { type: String, default: 'chart' },
      theme: { type: String, default: 'macarons' },
      autoResize: { type: Boolean, default: true },
      watchShallow: { type: Boolean, default: true },
      width: { type: String, default: '100%' },
      height: { type: String, default: '250px' }
    },
    data() {
      return {
        options: this.buildOptions(this.chartData)
      }
    },
    watch: {
      chartData: {
        deep: true,
        handler(val) {
          this.options = this.buildOptions(val)
        }
      }
    },
    mounted() {
      if (!this.options && this.chartData) {
        this.options = this.buildOptions(this.chartData)
      }
    },
    methods: {
      buildOptions(chartData) {
        if (!chartData) {
          return
        }
        var legendData = ['metadata', 'hbase']
        var seriesData = [{ name: 'metadata', value: chartData.metadata },
          { name: 'hbase', value: chartData.hbase }]
        var seriesName = '存储（' + chartData.date + '）'
        var unit = chartData.unit
        var titleText = '总计\n' + Number(chartData.metadata + chartData.hbase).toFixed(2)

        return {
          title: {
            text: titleText,
            x: 'center',
            y: 'center',
            textStyle: {
              fontSize: '25'
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c}' + unit + ' ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: '2%',
            y: 'center',
            data: legendData
          },
          series: {
            name: seriesName,
            type: 'pie',
            radius: ['40%', '80%'],
            center: ['50%', '50%'],
            label: {
              show: true,
              normal: {
                position: 'inner',
                formatter: function(param) {
                  return Number(param.value).toFixed(2)
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: seriesData
          }
        }
      }
    }
  }
</script>
